from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection

from rest_framework.views import APIView
from rest_framework.response import Response
from users.models import User, Address
from users.utils import generic_verify_url


class RegisterUsernameCountAPIView(APIView):
    """
    获取用户名的个数
    GET:  /users/usernames/(?P<username>\w{5,20})/count/
    """

    def get(self,request,username):

        #通过模型查询,获取用户名个数
        count = User.objects.filter(username=username).count()
        #组织数据
        context = {
            'count':count,
            'username':username
        }
        return Response(context)



from rest_framework.views import APIView
from rest_framework.response import Response
from .models import User
# Create your views here.

class RegisterPhoneCountAPIView(APIView):
    """
    查询手机号的个数
    GET: /users/phones/(?P<mobile>1[345789]\d{9})/count/
    """
    def get(self,request,mobile):

        #通过模型查询获取手机号个数
        count = User.objects.filter(mobile=mobile).count()
        #组织数据
        context = {
            'count':count,
            'phone':mobile
        }

        return Response(context)



# from rest_framework.generics import CreateAPIView
# from .serializers import RegisterCreateSerializer
# Create your views here.

# class RegisterCreateView(CreateAPIView):
#     """
#     用户注册
#     POST /users/
#
#     用户注册我们需要对数据进行校验,同时需要数据入库
#     """
#
#     serializer_class = RegisterCreateSerializer

# class RegisterUserAPIView(APIView):
#     def post(self,request):
#         data = request.data
#         serializer = RegisterCreateSerializer(data=data)
#         serializer.is_valid(raise_exception=True)
#         user = serializer.save()
#
#
#         from rest_framework_jwt.settings import api_settings
#
#         jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
#         jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
#
#         payload = jwt_payload_handler(user)
#         token = jwt_encode_handler(payload)
#
#
#         # 将token返回回去
#         data = serializer.data
#         data['token']=token
#
#         return Response(data)


from rest_framework.generics import CreateAPIView
from .serializers import RegisterCreateSerializer, UserCenterInfoSerializer, EmailUpdateSerializer, \
    AddressesCreateSerializer


class RegisterCreateView1(CreateAPIView):
    serializer_class = RegisterCreateSerializer



# from rest_framework.permissions import IsAuthenticated
# class UserCenterInfoAPIView(APIView):
#
#     # 这个接口 只能是登陆用户才能访问
#     permission_classes = [IsAuthenticated]
#
#     def get(self,request):
#
#         #1. 接收用户信息
#         # 在这里 结合用户权限 我们就获取到了 用户信息
#         user = request.user
#         #2. 将对象转换为字典
#         serializer = UserCenterInfoSerializer(user)
#         #3. 返回数据
#         return Response(serializer.data)

from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import RetrieveAPIView
class UserCenterInfoAPIView(RetrieveAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = UserCenterInfoSerializer
    def get_object(self):
        return self.request.user

class EmailUpdateAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def put(self,request):
        data = request.data
        # 3.更新指定用户的信息
        user = request.user

        serializer = EmailUpdateSerializer(instance=user,data=data)
        serializer.is_valid(raise_exception=True)

        serializer.save()

        from django.core.mail import send_mail

        # subject = '美多商场激活邮件'
        # message = '内容'
        # from_email = '美多商城<qi_rui_hua@163.com>'
        email = request.data.get('email')
        # recipient_list = [email]
        # html_message = '<a href="www.meiduo.site:8080">请点击</a>'

        verify_url = generic_verify_url(request.user.id,email)

        # html_message = '<p>尊敬的用户您好！</p>' \
        #                '<p>感谢您使用美多商城。</p>' \
        #                '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
        #                '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)

        # send_mail(subject=subject,
        #           message=message,
        #           from_email=from_email,
        #           recipient_list=recipient_list,
        #           html_message=html_message)
        from celery_tasks.email.tasks import send_verify_mail
        send_verify_mail.delay(email, verify_url)

        # 4.返回相应
        return Response(serializer.data)

from users.utils import check_active_token
from rest_framework import status
class EmailVerificationAPIView(APIView):

    def get(self,request):
        # 1.接收token
        token = request.query_params.get('token')
        if token is None:

            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 2.验证token
        data = check_active_token(token)
        if data is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 3.根据验证之后的数据进行查询
        user_id = data.get('user_id')
        email=data.get('email')
        # and
        # filter().filter()
        # filter(,,,,)
        try:
            user = User.objects.get(id=user_id,email=email)
        except User.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 4.修改用户的激活状态
        user.email_active=True
        user.save()
        # 5.返回相应
        return Response({'msg':'ok'})

# class EmailVerificationAPIView(APIView):
#     def get(self,request):
#         # 1.接收token
#
#         # 2.验证token并解密
#         # 3.根据获得的数据进行查询
#         # 4.修改激活状态
#         # 5.返回响应



class AddressesCreateAPIView(APIView):

    permission_classes = [IsAuthenticated]

    def post(self,request):
        # request.user

        # 1.接收数据
        # request.data 是没有 user信息的
        data = request.data
        # 2.验证数据
        serializer = AddressesCreateSerializer(data=data,context={'request':request})
        # 3.数据入库
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 4.返回相应
        return Response(serializer.data)


    # def get(self,request):
    #     # 1.查询对象的数据
    #     user = request.user
    #     id = user.id
    #     address = Address.objects.get(user_id=id)
    #     # 2.将模型对象转换为字典，many=true
    #     # serializer = AddressesCreateSerializer(address,many=True)
    #     # 3.返回响应字典数据
    #     return Response({
    #         'user_id':user.id,
    #         'default_address_id':user.default_address_id,
    #         'limit': 20,
    #         'addresses': serializer.data,
    #     })
    def get(self,request):
        user = request.user
        id = user.id
        address = Address.objects.filter(user_id=id)
        serializer = AddressesCreateSerializer(address,many=True)

        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data,
        })

    # def put(self,request,pk):
    #     # user = request.user
    #     # user_id = user.id
    #     address = Address.objects.get(user_id=user_id,id=pk)
    #     data = request.data
    #     # from users.serializers import AddressTitleSerializer
    #     serializer = AddressesCreateSerializer(address,data=data)
    #     serializer.is_valid(raise_exception=True)
    #     serializer.save()
    #     return Response({
    #         'user_id': user.id,
    #         'default_address_id': user.default_address_id,
    #         'limit': 20,
    #         'addresses': serializer.data,
    #     })


    def put(self,request,pk):
        # user = request.user
        # user_id = user.id
        address = Address.objects.get(id=pk)
        data = request.data
        # from users.serializers import AddressTitleSerializer
        serializer = AddressesCreateSerializer(address,data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    # def put(self, request, pk):
    #     # 1.接收参数
    #     address = Address.objects.get(id=pk)
    #     data = request.data
    #
    #     # 2.校验参数
    #     serializer = AddressesCreateSerializer(address, data=data)
    #     serializer.is_valid(raise_exception=True)
    #     # 3.数据入库
    #     serializer.save()
    #     # 4.返回数据
    #     return Response(serializer.data)






    # def delete(self, request, pk):
    #     user = request.user
    #     user_id = user.id
    #     address = Address.objects.filter(user_id=user_id,id=pk)
    #     address.delete()
    #     return Response({'message':'ok'})

    def delete(self, request, pk):
        # user = request.user
        # user_id = user.id
        address = Address.objects.filter(id=pk)
        address.delete()
        return Response({'message':'ok'})


class AddressStatus(APIView):
    def put(self,request,pk):
        # user = request.user
        # user_id = user.id
        address = Address.objects.get(id=pk)
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

from goods.models import SKU
from .serializers import UserHistroySerializer,SKUSerializer
class UserHistoryAPIView(CreateAPIView):

    permission_classes = [IsAuthenticated]

    serializer_class = UserHistroySerializer

    def get(self, request):
        # 接收用户的信息
        user = request.user
        # 根据用户的信息查询redis中的数据  [1,2,,3]
        redis_conn = get_redis_connection('history')
        ids = redis_conn.lrange('history_%s' % user.id, 0, 4)
        # 根据id查询商品的信息             [sku，sku,sku]
        # skus = SKU.objects.filter(pk__in=ids)
        # SKU.objects.filter(pk__in=ids) 原有的顺序就不存在了

        skus = []

        for sku_id in ids:
            sku = SKU.objects.get(pk=sku_id)
            skus.append(sku)

        # 将对象列表转换为字典列表
        serializer = SKUSerializer(skus, many=True)
        # 返回相应
        return Response(serializer.data)


from rest_framework_jwt.views import ObtainJSONWebToken
from cart.utils import merge_cookie_to_redis

class UserAuthorizationView(ObtainJSONWebToken):

    def post(self, request):
        # 调用jwt扩展的方法，对用户登录的数据进行验证
        response = super().post(request)

        # 如果用户登录成功，进行购物车数据合并
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 表示用户登录成功
            user = serializer.validated_data.get("user")
            # 合并购物车
            #merge_cart_cookie_to_redis(request, user, response)
            response = merge_cookie_to_redis(request, user, response)

        return response

#修改密码
from users.serializers import Updateserializer
class UpdateApive(APIView):
    permission_classes = [IsAuthenticated]
    def put(self,request,pk):
        data = request.data
        # data['id']=pk
        # print(data)
        # user = User.objects.get(pk =pk)
        user = request.user
        serializer = Updateserializer(data=data,instance=user,context={'request':request})
        serializer.is_valid(raise_exception=True)
        serializer.save()

        print(serializer.data)
        return Response(serializer.data)



#忘记密码
import random
import re


from users.utils import get_tjws_token,decode_jws_token,get_password_token,decode_password_token
class VerifyAccountAPIView(APIView):
    def get(self,request,username):
        image_code_id = request.query_params.get('image_code_id')
        image_code = request.query_params.get('text')
        try:
            if re.match(r'1[3-9]\d{9}', username):
                user = User.objects.get(mobile=username)
                username = user.username
            else:
                user = User.objects.get(username=username)
        except:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        redis_conn = get_redis_connection('code')
        real_image_code = redis_conn.get('img_%s' % image_code_id).decode()
        if real_image_code.upper() != image_code.upper():
            return Response(status=status.HTTP_400_BAD_REQUEST)
        token = get_tjws_token(username, user.mobile)
        mobile = user.mobile
        mobile_l = mobile[0:3]
        mobile_r = mobile[7:12]
        mobile = ('%s****%s' % (mobile_l,mobile_r))
        data = {
            'mobile':mobile,
            'access_token':token
        }

        return Response(data)


class PasswordSmscodeAPIView(APIView):
    def get(self,request):
        access_token = request.query_params['access_token']
        data = decode_jws_token(access_token)
        if not data:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        username = data['username']
        try:
            user = User.objects.get(username=username)
            mobile = user.mobile
        except User.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        sms_code = '%06d' % random.randint(0, 999999)
        from celery_tasks.sms.tasks import send_sms_code
        # CCP().send_template_sms(mobile,[sms_code,5],1)
        send_sms_code.delay(mobile, sms_code)
        redis_conn = get_redis_connection('code')
        redis_conn.setex("sms_%s" % mobile, 300, sms_code)
        print(sms_code)
        return Response({'msg': 'ok'})


class VSmscodeAPIView(APIView):
    def get(self,request,username):
        sms_code = request.query_params['sms_code']
        try:
            if re.match(r'1[3-9]\d{9}', username):
                user = User.objects.get(mobile=username)
                username = user.username
                mobile = user.mobile
            else:
                user = User.objects.get(username=username)
                mobile = user.mobile
        except User.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        redis_conn = get_redis_connection('code')
        redis_sms = redis_conn.get("sms_%s" % mobile).decode()
        if redis_sms != sms_code:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        token = get_password_token(mobile)
        print(token)
        result = {
            'user_id':user.id,
            'access_token': token
        }

        return Response(result)

    def post(self,request,user_id):
        token = request.data.get('access_token')
        password = request.data.get('password')
        password2 = request.data.get('password2')
        if password != password2:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        mobile = decode_password_token(token)
        mobile = mobile['mobile']
        try:
            user = User.objects.get(mobile=mobile,id=user_id)
        except:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        user.set_password(password)
        user.save()
        return Response({'msg': 'ok'})
